package com.sell.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.sell.VO.PayVO;
import com.sell.dto.OrderDTO;
import com.sell.service.OrderService;
import com.sell.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: Xukai
 * Description:
 * CreateDate: 2018/6/26 13:23
 * Modified By:
 */
@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId, @RequestParam("returnUrl") String returnUrl, HttpServletRequest request) {
        // 查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        //发起支付
        PayVO payVO = payService.create(orderDTO, request);
        ModelAndView mav = new ModelAndView();
        mav.addObject("payVO", payVO);
        mav.addObject("returnUrl", returnUrl);
        mav.setViewName("pay/create");
        return mav;
    }

    /*
     * Author: XuKai
     * Description: 微信支付的异步通知
     * Created: 2018/6/27 16:25
     * Params: [notifyData]
     * Returns: void
     */
    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestBody String notifyData) {
        try {
            payService.notify(notifyData);
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }
}
